package com.zyj.web.controller.system;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zyj.common.core.domain.entity.*;
import com.zyj.report.domain.AssetsReportRepairs;
import com.zyj.report.service.IAssetsReportRepairsService;
import com.zyj.system.service.ISysDeptService;
import com.zyj.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zyj.common.config.ZyjConfig;
import com.zyj.common.constant.ShiroConstants;
import com.zyj.common.core.controller.BaseController;
import com.zyj.common.core.domain.AjaxResult;
import com.zyj.common.core.text.Convert;
import com.zyj.common.utils.CookieUtils;
import com.zyj.common.utils.DateUtils;
import com.zyj.common.utils.ServletUtils;
import com.zyj.common.utils.StringUtils;
import com.zyj.framework.shiro.service.SysPasswordService;
import com.zyj.system.service.ISysConfigService;
import com.zyj.system.service.ISysMenuService;

/**
 * 首页 业务处理
 * 

 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IAssetsReportRepairsService assetsReportRepairsService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDeptService deptService;



    // 系统首页
    @GetMapping("/index")
    public String index(HttpServletRequest request,ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(configService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(configService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
        mmap.put("copyrightYear", ZyjConfig.getCopyrightYear());
        mmap.put("demoEnabled", ZyjConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登录");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        //默认普通用户
        String mainpage = "main_common";
        mmap.put("version", ZyjConfig.getVersion());
        mmap.put("userid", getUserId());
        //获取登录用户角色
        List<SysRole> roles = getSysUser().getRoles();
        if(roles!=null && !roles.isEmpty()){
            for(int i=0;i<roles.size();i++){
                SysRole role = roles.get(i);
                long rolesid = role.getRoleId();
                String rolesname = role.getRoleName();
                //判断是否管理员
                if(rolesid==1 || rolesid==3 || rolesid==4){
                    //判断是否维修员或管理员
                    //获取维修员主页的统计数据
                    AssetsReportRepairs assetsReportRepairs = new AssetsReportRepairs();
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("beginCreateTime",DateUtils.getDate()+" 00:00:00");
                    params.put("endCreateTime", DateUtils.getDate() + " 23:59:59");
                    assetsReportRepairs.setParams(params);
                    //资产维修情况
                    List<AssetsReportRepairs> report = assetsReportRepairsService.selectAssetsReportRepairsList(assetsReportRepairs);
                    if(report!=null && !report.isEmpty()) {
                        AssetsReportRepairs r = report.get(0);
                        long allnum = r.getAllNum();
                        long donenum = r.getDoneNum();
                        long repairnum = r.getRepairsNum();
                        long screpNum = r.getScrepNum();
                        r.setCreateTimeStr(DateUtils.dateTime(r.getCreateTime()));
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(2);
                        r.setDonePercent(numberFormat.format((float) donenum / (float) allnum * 100));
                        r.setRepairsPercent(numberFormat.format((float) repairnum / (float) allnum * 100));
                        r.setScrepPercent(numberFormat.format((float) screpNum / (float) allnum * 100));
                        mmap.put("report", r);
                    }
                    //资产状态占比
                    SysDictData dictData = new SysDictData();
                    dictData.setDictType("assets_status");
                    List<SysDictData> dictDataList = dictDataService.selectDictDataList(dictData);
                    List<AssetsReportRepairs> assetsReport = assetsReportRepairsService.selectAssetsReport();
                    String [] dictDataStr = new String[dictDataList.size()];
                    Map [] dictDataValueStr = new Map[dictDataList.size()];
                    for(int j=0;j<dictDataList.size();j++){
                        dictData = dictDataList.get(j);
                        for(int k=0;k<assetsReport.size();k++){
                            AssetsReportRepairs r= assetsReport.get(k);
                            if((String.valueOf(r.getId())).equals(dictData.getDictValue())){
                                String lable = dictData.getDictLabel()+" ("+r.getAllNum()+")";
                                Map _m = new HashMap<>();
                                _m.put("value",r.getAllNum());
                                _m.put("name",lable);
                                dictDataValueStr[j]=_m;
                                dictDataStr[j]=lable;
                                continue;
                            }
                        }
                    }
                    mmap.put("dictData", dictDataStr);
                    mmap.put("dictDataValue", dictDataValueStr);

                    //资产分类统计
                    SysDictData assetsTypeData = new SysDictData();
                    assetsTypeData.setDictType("assets_type");
                    List<SysDictData> assetsTypeDataList = dictDataService.selectDictDataList(assetsTypeData);
                    List<AssetsReportRepairs> assetsTypeReport = assetsReportRepairsService.selectAssetsTypeReport();
                    String [] assetsTypeDataStr = new String[assetsTypeDataList.size()];
                    long [] assetsTypeValueStr = new long[assetsTypeDataList.size()];
                    for(int j=0;j<assetsTypeDataList.size();j++) {
                        assetsTypeData = assetsTypeDataList.get(j);
                        String lable = assetsTypeData.getDictLabel();

                        for(int k=0;k<assetsTypeReport.size();k++){
                            AssetsReportRepairs r= assetsTypeReport.get(k);
                            if((String.valueOf(r.getId())).equals(assetsTypeData.getDictValue())){
                                assetsTypeValueStr[j]=r.getAllNum();
                                assetsTypeDataStr[j]=lable;
                                continue;
                            }
                        }

                    }
                    mmap.put("assetsTypeData", assetsTypeDataStr);
                    mmap.put("assetsTypeValue", assetsTypeValueStr);

                    //部门资产统计
                    List<SysDept> deptList = deptService.selectDeptList(new SysDept());
                    List<String> assetsDeptDataList = new ArrayList<>();
                    List<Long> assetsDeptValueList = new ArrayList<>();
                    for(int j=0;j<deptList.size();j++) {
                        SysDept dept = deptList.get(j);
                        long deptid = dept.getDeptId();
                        if(!deptService.checkDeptExistUser(deptid)){
                            continue;
                        }
                        long count = deptService.selectDeptAssetsCount(deptid);
                        if(count>0) {
                            assetsDeptDataList.add(dept.getDeptName());
                            assetsDeptValueList.add(deptService.selectDeptAssetsCount(deptid));
                        }
                    }
                    mmap.put("assetsDeptData", assetsDeptDataList.toArray());
                    mmap.put("assetsDeptValue", assetsDeptValueList.toArray());

                    mainpage = "main_repairs";
                }
            }
        }
        return mainpage;
    }

    // content-main class
    public String contentMainClass(Boolean footer, Boolean tagsView)
    {
        if (!footer && !tagsView)
        {
            return "tagsview-footer-hide";
        }
        else if (!footer)
        {
            return "footer-hide";
        }
        else if (!tagsView)
        {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
